﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;

namespace LabMS.Web
{
    public partial class AddScore : Base.BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            strPagePrivilege.Add("SYSCJLR");
            strPageUserType.Add("teacher");
            strPageUserType.Add("mana");
            if (Request.QueryString["ID"] != null)
            {
                if (!IsPostBack)
                {
                    int ID;
                    if (int.TryParse(Request.QueryString["ID"].ToString(), out ID))
                    {
                        IDHF.Value = ID.ToString();
                        int CourseID, ClassID;
                        SubjectDDL_DataBind(ID);//绑定项目
                        ClassDDL_DataBind(ID);//绑定班级
                        if (ClassDDL.SelectedValue == "")
                        {
                            Page.ClientScript.RegisterClientScriptBlock(GetType(), "", "<script type='text/javascript'>alert('该课程暂无选课班级！');self.close()</script>");
                            return;
                        }
                        BindData(ID);
                        if (int.TryParse(SubjectDDL.SelectedValue, out CourseID) && int.TryParse(ClassDDL.SelectedValue, out ClassID))
                        {
                            ScoreGridView_DataBind(ClassID, CourseID);
                        }
                    }
                    else
                    {
                        ERRLbl.Text = "系统异常，参数值不合法！";
                        ERRLbl.Visible = true;
                        SaveBtn.Visible = false;
                    }
                }
            }
            else
            {
                ERRLbl.Text = "系统异常，参数值不合法！";
                ERRLbl.Visible = true;
                SaveBtn.Visible = false;
            }
            CourseCodeTBX.Attributes.Add("readOnly", "-1");
            CourseNameTBX.Attributes.Add("readOnly", "-1");
            ProjectName.Attributes.Add("readOnly", "-1");
            ExprientHouseTBX.Attributes.Add("readOnly", "-1");
            TeacherTBX.Attributes.Add("readOnly", "-1");
            SumTBX.Attributes.Add("readOnly", "-1");
            ClassTBX.Attributes.Add("readOnly", "-1");
        }

        //绑定数据
        protected void BindData(int ID)
        {
            LabMS.Model.ClassItem model = new LabMS.Model.ClassItem();
            LabMS.BLL.Course course = new LabMS.BLL.Course();
            LabMS.Model.Course courseModel = new LabMS.Model.Course();
            courseModel = course.GetModel(ID);
            model = GetClassName(ID);

            CourseCodeTBX.Text = courseModel.Course_Code;
            CourseNameTBX.Text = courseModel.Course_Name;
            ProjectName.Text = courseModel.Professional;//专业
            ClassTBX.Text = model.ClassItem_Name;//班级
            SumTBX.Text = model.ClassItem_Num.ToString();//总人数
            if (SubjectDDL.SelectedValue != "")
            {
                ExprientHouseTBX.Text = GetExHourByProID(int.Parse(SubjectDDL.SelectedValue));//实验学时
                TeacherTBX.Text = GetTeacherByClaIDAndProIDAndCouID(int.Parse(IDHF.Value), int.Parse(SubjectDDL.SelectedValue), int.Parse(ClassDDL.SelectedValue));//授课教师
            }
            
        }

        //绑定gridview
        protected void ScoreGridView_DataBind(int ClassID, int ProjectID)
        {
            ExtendBLL.Score score = new ExtendBLL.Score();
            DataSet ds = new DataSet();
            int proCouID;

            proCouID = GetProCourseIDByProID(ProjectID,int.Parse(IDHF.Value));
            try
            {
                ds = score.GetScoreInfo(ClassID, proCouID);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            if (ds.Tables.Count != 0)
            {
                ScoreGridView.DataSource = ds;
                ScoreGridView.DataBind();
            }
            else
            {
                SaveBtn.Visible = false;
                ConcelBtn.Visible=false;
                MessLbl.Visible = true;
                MessLbl.Text = "暂无学生数据";
            }
        }

        //dropDownList索引改变
        protected void DropDownList_OnSelectIndexChange(object sender, EventArgs e)
        {
            int ProjectID, ClassID;
            if (int.TryParse(SubjectDDL.SelectedValue, out ProjectID) && int.TryParse(ClassDDL.SelectedValue, out ClassID))
            {
                TeacherTBX.Text = GetTeacherByClaIDAndProIDAndCouID(int.Parse(IDHF.Value), ProjectID, ClassID);//授课教师
                ExprientHouseTBX.Text = GetExHourByProID(ProjectID);//实验学时
                ScoreGridView_DataBind(ClassID, ProjectID);
            }
        }

        //获取课程基本信息
        protected void GetCourseInfo(int ID)
        {
            LabMS.BLL.Course course = new LabMS.BLL.Course();
            LabMS.Model.Course courseModel = new LabMS.Model.Course();

            courseModel = course.GetModel(ID);
        }

        //获取选课班级 总人数
        protected LabMS.Model.ClassItem GetClassName(int ID)
        {
            LabMS.BLL.ClassItem classItem = new LabMS.BLL.ClassItem();
            List<LabMS.Model.ClassItem> classItemModel = new List<LabMS.Model.ClassItem>();
            LabMS.Model.ClassItem cIModel = new LabMS.Model.ClassItem();
            string str;
            cIModel.ClassItem_Name = "";
            cIModel.ClassItem_Num = 0;
            classItemModel = classItem.GetModelList("CourseID=" + ID);
            for (int i = 0; i < classItemModel.Count; i++)
            {
                cIModel.ClassItem_Name += classItemModel[i].ClassItem_Name+",";
                cIModel.ClassItem_Num += classItemModel[i].ClassItem_Num;
            }
            str = cIModel.ClassItem_Name;
            cIModel.ClassItem_Name = str.Substring(0, str.Length - 1);
            return cIModel;
        }

        //通过班级ID获取选课班级ID
        protected int GetCouClaIDByClaID(int CID,int IID)
        {
            LabMS.BLL.ClassItem claItem = new LabMS.BLL.ClassItem();
            List<LabMS.Model.ClassItem> claItemModel = new List<LabMS.Model.ClassItem>();
            int CIID = 0;

            claItemModel = claItem.GetModelList("ClassID=" + CID + " and CourseID=" + IID);
            if (claItemModel.Count != 0)
            {
                CIID = claItemModel[0].ID;
            }
            return CIID;
        }
        //通过项目ID和课程ID获取课程项目ID
        protected int GetProCourseIDByProID(int PID,int CID)
        {
            LabMS.BLL.CourseAndProject proCou = new LabMS.BLL.CourseAndProject();
            List<LabMS.Model.CourseAndProject> proCouModel = new List<LabMS.Model.CourseAndProject>();
            int PCID=0;

            proCouModel = proCou.GetModelList("ProjectID=" + PID + " and CourseID=" + CID);
            if (proCouModel.Count != 0)
            {
                PCID = proCouModel[0].ID;
            }
            return PCID;
        }

        //通过项目ID获取实验学时
        protected string GetExHourByProID(int ProjectID)
        {
            LabMS.BLL.Project pro = new LabMS.BLL.Project();
            LabMS.Model.Project proModel = new LabMS.Model.Project();
            string Hour;

            proModel = pro.GetModel(ProjectID);
            Hour = proModel.Project_ClassHourse.ToString();
            return Hour;
        }

        //获取授课教师 通过项目ID 班级ID 课程ID
        protected string GetTeacherByClaIDAndProIDAndCouID(int CourseID,int ProjectID,int ClassID)
        {
            LabMS.BLL.Arrangement arr = new LabMS.BLL.Arrangement();
            List<LabMS.Model.Arrangement> arrModel = new List<LabMS.Model.Arrangement>();
            int ProCouID,ClaCouID;
            string TeacherName;

            ProCouID = GetProCourseIDByProID(ProjectID, CourseID);
            ClaCouID = GetCouClaIDByClaID(ClassID, CourseID);

            arrModel = arr.GetModelList("ChoosenClassID=" + ClaCouID + " and CourseProjectID=" + ProCouID);
            TeacherName = HandTeaList(arrModel);
            return TeacherName;
        }

        //遍历老师列表
        protected string HandTeaList(List<LabMS.Model.Arrangement> arrList)
        {
            string str = "";
            for (int i = 0; i < arrList.Count; i++)
            {
                str += arrList[i].TeacherName+",";
            }
            if (str != "")
            {
                str = str.Substring(0, str.Length - 1);
            }
            return str;
        }
        //绑定实验项目
        protected void SubjectDDL_DataBind(int CourseID)
        {
            ExtendBLL.Score score = new ExtendBLL.Score();
            DataSet ds = new DataSet();
            ds = score.GetSubjectInfoByCourseID(CourseID);
            if (ds.Tables.Count != 0)
            {
                
                SubjectDDL.DataSource = ds;
                SubjectDDL.DataBind();
            }
        }

        //绑定班级
        protected void ClassDDL_DataBind(int CourseID)
        {
            LabMS.BLL.ClassItem classItem = new LabMS.BLL.ClassItem();
            List<LabMS.Model.ClassItem> classItemModel = new List<LabMS.Model.ClassItem>();

            classItemModel = classItem.GetModelList("CourseID=" + CourseID);
            ClassDDL.DataSource = classItemModel;
            ClassDDL.DataBind();
        }

        //分页
        protected void ScoreGV_OnPageIndexChang(object sender, GridViewPageEventArgs e)
        {
            ScoreGridView.PageIndex = e.NewPageIndex;
            ScoreGridView_DataBind(int.Parse(ClassDDL.SelectedValue), int.Parse(SubjectDDL.SelectedValue));
        }

        //检查是否已存在学生课程成绩信息
        protected int CheckIsScore(int? ProjectCourseID, int? StudentID)
        {
            LabMS.BLL.Score sco = new LabMS.BLL.Score();
            List<LabMS.Model.Score> scoModelList = new List<LabMS.Model.Score>();

            scoModelList = sco.GetModelList("ProjectCourseID=" + ProjectCourseID + "and StudentID=" + StudentID);
            if (scoModelList.Count > 0)
            {
                return scoModelList[0].ID;
            }
            else
                return -1;
        }

        //保存成绩
        protected void Save_OnClick(object sender, EventArgs e)
        {

            List<LabMS.Model.Score> list = new List<LabMS.Model.Score>();
            string[] str = new string[4];

            int count = ScoreGridView.Rows.Count;
            if (count == 0)
            {
                return;
            }
            int[] iarray = new int[count];
            for (int i = 0; i < count; i++)
            {
                LabMS.Model.Score scoreModel = new LabMS.Model.Score(); 
                TextBox optb = (TextBox)ScoreGridView.Rows[i].FindControl("OpScoreTBX");
                TextBox pretb = (TextBox)ScoreGridView.Rows[i].FindControl("PreScoreTBX");
                TextBox extb = (TextBox)ScoreGridView.Rows[i].FindControl("ExScoreTBX");
                TextBox stb = (TextBox)ScoreGridView.Rows[i].FindControl("ScoreTBX");
                int IsScore;

                scoreModel.ProjectCourseID = GetProCourseIDByProID(int.Parse(SubjectDDL.SelectedValue), int.Parse(IDHF.Value));
                scoreModel.StudentID = int.Parse(ScoreGridView.DataKeys[i]["StudentID"].ToString());

                IsScore = CheckIsScore(scoreModel.ProjectCourseID, scoreModel.StudentID);

                if (IsScore>0)//更新
                {
                    iarray[i] = 1;
                    int iOut;
                    if(optb.Text.Trim() != "")
                    {
                        if (int.TryParse(optb.Text.Trim(), out iOut))
                            scoreModel.Score_Op = iOut;
                    }
                    if(pretb.Text.Trim() != "")
                    {
                        if (int.TryParse(pretb.Text.Trim(), out iOut))
                            scoreModel.Score_Pre = iOut;
                    }
                    if (extb.Text.Trim() != "")
                    {
                        if (int.TryParse(extb.Text.Trim(), out iOut))
                            scoreModel.Score_Ex = iOut;
                    }
                    if (stb.Text.Trim() != "")
                    {
                        if (int.TryParse(stb.Text.Trim(), out iOut))
                            scoreModel.MScore = iOut;
                    }
                    scoreModel.ID = IsScore;
                    list.Add(scoreModel);
                }
                else//插入
                {
                    iarray[i] = 0;
                    int iOut;
                    if (optb.Text.Trim() != "")
                    {
                        if (int.TryParse(optb.Text.Trim(), out iOut))
                            scoreModel.Score_Op = iOut;
                    }
                    if (pretb.Text.Trim() != "")
                    {
                        if (int.TryParse(pretb.Text.Trim(), out iOut))
                            scoreModel.Score_Pre = iOut;
                    }
                    if (extb.Text.Trim() != "")
                    {
                        if (int.TryParse(extb.Text.Trim(), out iOut))
                            scoreModel.Score_Ex = iOut;
                    }
                    if (stb.Text.Trim() != "")
                    {
                        if (int.TryParse(stb.Text.Trim(), out iOut))
                            scoreModel.MScore = iOut;
                    }
                    if (IDHF.Value != "0")
                    {
                        scoreModel.CourseID = int.Parse(IDHF.Value);
                    }
                    scoreModel.CourseName = CourseNameTBX.Text.Trim();
                    if (ClassDDL.SelectedValue != "")
                    {
                        if (int.TryParse(ClassDDL.SelectedValue, out iOut))
                            scoreModel.ClassID = iOut;
                    }
                    //scoreModel.ProjectCourseID = GetProCourseIDByProID(int.Parse(SubjectDDL.SelectedValue), int.Parse(IDHF.Value));
                    scoreModel.ClassItemID = GetCouClaIDByClaID(int.Parse(ClassDDL.SelectedValue), int.Parse(IDHF.Value));
                    scoreModel.Score_Percent = "";
                    scoreModel.StudentCode = ScoreGridView.Rows[i].Cells[0].Text;
                    //scoreModel.StudentID = int.Parse(ScoreGridView.DataKeys[i]["StudentID"].ToString());
                    //scoreModel.ID = int.Parse(ScoreGridView.DataKeys[i]["ID"].ToString());
                    scoreModel.StudentName = ScoreGridView.Rows[i].Cells[1].Text;
                    list.Add(scoreModel);
                }
            }
            ExtendBLL.Score scoreExt = new ExtendBLL.Score();
            try
            {
                scoreExt.AddScore(iarray, list);
                LabMS.Common.JShelper.JSAlert(Page, "script", "添加成功!");
            }
            catch
            {
                LabMS.Common.JShelper.JSAlert(Page, "script", "添加失败!");
            }

        }

        protected void CreatScore_OnClick(object sender, EventArgs e)
        {
            for (int i = 0; i < ScoreGridView.Rows.Count; i++)
            {
                TextBox optb = (TextBox)ScoreGridView.Rows[i].FindControl("OpScoreTBX");
                TextBox pretb = (TextBox)ScoreGridView.Rows[i].FindControl("PreScoreTBX");
                TextBox extb = (TextBox)ScoreGridView.Rows[i].FindControl("ExScoreTBX");
                float score=0;
                if (MothodDDL.SelectedValue == "0")
                {
                    try
                    {
                        if (optb.Text.Trim() != "")
                        {
                            score += float.Parse(optb.Text.Trim());
                        }
                        if (pretb.Text.Trim() != "")
                        {
                            score += float.Parse(pretb.Text.Trim());
                        }
                        if (extb.Text.Trim() != "")
                        {
                            score += float.Parse(extb.Text.Trim());
                        }
                        ScoreGridView.Rows[i].Cells[5].Text = int.Parse(score.ToString()).ToString();
                    }
                    catch
                    {
                        i++;
                        Page.ClientScript.RegisterClientScriptBlock(GetType(), "", "<script type='text/javascript'>alert('第" + i + "行成绩输入不合法')</script>");
                        return;
                    }
                }
                else if (MothodDDL.SelectedValue=="1")
                {
                    //try
                    //{
                        if (optb.Text.Trim() != "" && OpTBX.Text.Trim() !="")
                        {
                            score += float.Parse(optb.Text.Trim()) * float.Parse(OpTBX.Text.Trim())/100;
                        }
                        if (pretb.Text.Trim() != "" && PreTBX.Text.Trim()!="")
                        {
                            score += float.Parse(pretb.Text.Trim()) * float.Parse(PreTBX.Text.Trim()) / 100;
                        }
                        if (extb.Text.Trim() != "" && ExTBX.Text.Trim()!="")
                        {
                            score += float.Parse(extb.Text.Trim()) * float.Parse(ExTBX.Text.Trim()) / 100;
                        }
                        ScoreGridView.Rows[i].Cells[5].Text = RoundingOff(score).ToString();
                    //}
                    //catch
                    //{
                    //    i++;
                    //    Page.ClientScript.RegisterClientScriptBlock(GetType(), "", "<script type='text/javascript'>alert('第" + i + "行成绩或成绩权值输入不合法')</script>");
                    //    return;
                    //}
                }
            }


        }

        private int RoundingOff(float source)
        {
            int integer = Convert.ToInt32(source);
            if (source - integer > 0.5)
            {
                integer++;
            }
            return integer;
        }

        protected void Concel_OnClick(object sender, EventArgs e)
        {
            Page.ClientScript.RegisterClientScriptBlock(GetType(), "", "<script type='text/javascript'>window.location.href =window.location;</script>");
            return;
        }
    }
}
